/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

/**
 * Default variables
 */
var icon_load = "";

/**
 * Onload actions
 */
$(function()
{
    // Set some default vars
    icon_load   = 'http://localhost'+baseUrl+'/images/loading.gif';
    
    // Enable jQuery TABS
    $("#tabs").tabs();
    
    // Pagination
    paginate('.block-readinglist .pagination a', 'index', 'pagebooks');
    paginate('.block-announcements .pagination a', 'index', 'pageannounoucements');
    paginate('.block-courses .pagination a', 'index', 'pagecourses');
    paginate('.block-notes .pagination a', 'index', 'pagenotes');
    paginate('.block-newbooks .pagination a', 'book', 'pagenewbooks');
    paginate('.block-mybooks .pagination a', 'book', 'pagemybooks');
    paginate('.block-allcourses .pagination a', 'course', 'pageallcourses');
    paginate('.block-mycourses .pagination a', 'course', 'pagemycourses');
    paginate('.block-recentcourses .pagination a', 'course', 'pagerecentcourses');
    paginate('.block-course-announcements .pagination a', 'course', 'pageannounces/id/'+$('#course_id').val()+'');
    paginate('.block-course-books .pagination a', 'course', 'pagebooks/id/'+$('#course_id').val()+'');
    paginate('.block-allbooks .pagination a', 'book', 'pageallbooks');
    paginate('.block-userlist .pagination a', 'user', 'pageusers');
    paginate('.books-book-reviews-container .pagination a', 'book', 'pagereviews/id/'+$('#book_id').val()+'');
    paginate('.books-article-notes-container .pagination a', 'book', 'pagenotes/id/'+$('#article_id').val()+'');
    
    paginate('.block-author-courses .pagination a', 'senior', 'pagecourses');
    paginate('.block-author-books .pagination a', 'senior', 'pagebooks');
    paginate('.block-author-announcements .pagination a', 'senior', 'pageannounces');
    paginate('.block-author-chapters .pagination a', 'senior', 'pagechapters');
    paginate('.block-author-articles .pagination a', 'senior', 'pagearticles');
    // Ajax forms
    addReview();
    addNote();
});

/**
 * Go to a hash tab
 */
function goToHashTab(hash)
{
    $('#tabs').tabs('select', '#'+hash);
}

function getPagerUrl(controller, request) {
    return baseUrl+'/'+controller+'/ajaxrequest/req/'+request+'/p/';
}

function paginate(selector, controller, request)
{
    var link_base   = getPagerUrl(controller, request);
    $(selector).live('click', function(event)
    {
        // Get the vars we need
        var alink   = $(this).attr('href');
        var chunks  = alink.split('/');
        var page_nr = chunks[chunks.length-1];
        // Load page
        loadPagedPage(this, link_base, page_nr);
        // Prevent this link from activating
        event.stopPropagation();
        return false;
    });
}

function loadPagedPage(element, link, page_nr) {
    // Delete the layout
    $(element).parents('.feed').children('.list').html('<img src="'+icon_load+'" class="loading" />');
    // Make the AJAX call
    $(element).parents('.feed').load(link+page_nr);
}

function addReview()
{
    $('#addreview').click(function(event)
    {
        // Store the button
        var button  = $(this);
        // Hide this link
        button.hide();
        // Get the form container
        var form            = $(this).parent().parent().children('#reviewform');
        // Set the link to the form
        var addreviewurl    = baseUrl+'/book/addreview/id/'+$('#book_id').val();
        // Load the form to the container
        form.load(addreviewurl);
        // Add event to submit button
        $('#review_add').live('click', function(event)
        {
            // Disable button for now
            $(this).attr('disabled', 'disabled');
            // Get the form values
            var values  = {};
            $.each($(this).parents('form').serializeArray(), function(i, field) {
                values[field.name]  = field.value;
            });
            // Submit form
            $.ajax({
                type: 'POST',
                url: addreviewurl,
                data: values,
                success: function(data) {
                    if(data.result == true)
                    {
                        // Item saved, reload reviews
                        loadPagedPage('.books-book-reviews-container .feed section', getPagerUrl('book', 'pagereviews/id/'+$('#book_id').val()+''), 1);
                        // Remove listeners
                        $('#review_add').unbind();
                        $('#review_add').die();
                        // Clear the form
                        form.html("");
                        // Show the add review button again
                        button.show();
                    }
                    else
                    {
                        // Error, show form again
                        form.html(data.form);
                    }
                },
                error: function(data) {
                    // Grave error this, die in peace
                    alert("Ajax request failed.");
                },
                dataType: 'JSON'
            });
            // Prevent submit button from actually submitting
            event.stopPropagation();
            return false;
        });
        
        // Prevent this link from activating
        event.stopPropagation();
        return false;
    });
}

function addNote()
{
    $('#addnote').click(function(event)
    {
        // Store the button
        var button  = $(this);
        // Hide this link
        button.hide();
        // Get the form container
        var form            = $(this).parent().parent().children('#notesform');
        // Set the link to the form
        var addreviewurl    = baseUrl+'/book/addnote/id/'+$('#article_id').val();
        // Load the form to the container
        form.load(addreviewurl);
        // Add event to submit button
        $('#note_add').live('click', function(event)
        {
            // Get the form values
            var values  = {};
            $.each($(this).parents('form').serializeArray(), function(i, field) {
                values[field.name]  = field.value;
                // DEBUG FORM VALUES //
                // alert(field.name+': '+field.value);
            });
            // Submit form
            $.ajax({
                type: 'POST',
                url: addreviewurl,
                data: values,
                success: function(data) {
                    if(data.result == true)
                    {
                        // Item saved, reload reviews
                        loadPagedPage('.books-article-notes-container .feed section', getPagerUrl('book', 'pagenotes/id/'+$('#article_id').val()+''), 1);
                        // Remove listeners
                        $('#note_add').unbind();
                        $('#note_add').die();
                        // Clear the form
                        form.html("");
                        // Show the add review button again
                        button.show();
                    }
                    else
                    {
                        // Error, show form again
                        form.html(data.form);
                    }
                },
                error: function(data) {
                    // Grave error this, die in peace
                    console.log(data);
                    alert("Ajax request failed.");
                },
                dataType: 'JSON'
            });
            // Prevent submit button from actually submitting
            event.stopPropagation();
            return false;
        });
        
        // Prevent this link from activating
        event.stopPropagation();
        return false;
    });
}